package com.gin.no_gay_alliance.fragment.topic.list;


import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.exception.NgaException;
import com.gin.nga.method.NukeApi;
import com.gin.nga.response.body.BaseMessageBody;
import com.gin.nga.response.field.SubForum;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.TopicListActivity;
import com.gin.no_gay_alliance.adpter.base.BaseBindingRecyclerViewAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.CommonCallback;
import com.gin.no_gay_alliance.databinding.ItemSubForumBinding;
import com.gin.no_gay_alliance.param.TopicListParam;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.MenuUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.SubForumModel;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import okhttp3.Call;

/**
 * 浏览版面
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/5 12:34
 **/
public class ForumListFragment extends AbstractListFragment implements CompoundButton.OnCheckedChangeListener {

    /**
     * 创建选项菜单
     *
     * @param menu     菜单
     * @param inflater 渲染器
     */
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        // 装载精华区、子版面菜单
        inflater.inflate(R.menu.forum_list_menu, menu);
    }

    /**
     * 选项菜单的点击响应
     *
     * @param item 选项
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();

        // 打开精华区
        if (itemId == R.id.menu_item_recommend_area) {
            TopicListParam p = new TopicListParam();
            p.type = TopicListParam.Type.FORUM_RECOMMEND;
            p.forumId = param.forumId;
            p.title = param.title;
            // 启动活动
            TopicListActivity.startActivity(requireContext(), p);
            return true;
        }
        // 打开收藏夹
        if (itemId == R.id.menu_item_favor_folder) {
            TopicListActivity.startActivityFavor(requireContext());
        }

        //打开子版面列表
        if (itemId == R.id.menu_item_sub_forum) {
            // 子版面列表
            List<SubForum> subForums = forum.getSubForums();
            // 转换为 model
            List<SubForumModel> subForumModels = subForums.stream().map(SubForumModel::new).collect(Collectors.toList());
            // 构造弹窗
            RecyclerView rv = new RecyclerView(requireActivity());
            rv.setLayoutManager(new LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false));
            rv.setAdapter(new BaseBindingRecyclerViewAdapter<ItemSubForumBinding, SubForumModel>(requireActivity(), subForumModels) {
                @Override
                protected void onBindViewHolder(ViewHolder<ItemSubForumBinding> holder, @NonNull ItemSubForumBinding b, int position, SubForumModel item) {
                    // 初始化版面入口
                    b.forumEntryView.init(item, 0, 48);
                    // 选中状态
                    b.swSelected.setChecked(item.selected);
                    // 是否允许选中
                    ViewUtils.setGone(!item.selectable, b.swSelected);
                    // 把id放入tag ,用于切换操作
                    b.swSelected.setTag(item.id);
                    // 切换的操作
                    b.swSelected.setOnCheckedChangeListener(ForumListFragment.this);
                }

                @NonNull
                @Override
                protected ItemSubForumBinding buildBinding(LayoutInflater inflater) {
                    return ItemSubForumBinding.inflate(inflater);
                }
            });

            AlertDialogUtils.showConfirm(requireContext(), forum.getForumName() + " 的子版面", null, rv, null);
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 修改选项菜单项目可见性
     *
     * @param menu 菜单
     */
    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        // 当没有版面数据或子版面数据为空时，隐藏子版面按钮
        MenuUtils.setVisible(menu, forum != null && !ObjectUtils.isEmpty(forum.getSubForums()), R.id.menu_item_sub_forum);
    }

    /**
     * 切换子版面屏蔽开关时的操作
     *
     * @param buttonView 开关按钮
     * @param isChecked  是否选中
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (forumId == null) {
            toast("缺少版面id, 无法操作");
            // 回滚状态
            buttonView.setChecked(!isChecked);
            return;
        }
        Long id = (Long) buttonView.getTag();
        // 先禁用
        buttonView.setEnabled(false);
        // 执行操作的回调
        CommonCallback<BaseMessageBody> callback = new CommonCallback<BaseMessageBody>(handler) {
            @Override
            public void onSuccess(BaseMessageBody body) {
                toast(body.getMessage());
                ui(() -> buttonView.setEnabled(true));
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                super.onFailure(call, e);
                // 发生错误 回滚状态
                ui(() -> buttonView.setEnabled(!isChecked));
            }

            @Override
            public void handleException(NgaException e) {
                super.handleException(e);
                // 发生错误 回滚状态
                ui(() -> buttonView.setEnabled(!isChecked));
            }
        };
        if (isChecked) {
            // 选中操作
            NukeApi.blockSubForumDel(MyApplication.getClient(), forumId, id).async(callback);
        } else {
            // 取消操作
            NukeApi.blockSubForumAdd(MyApplication.getClient(), forumId, id).async(callback);
        }
    }

}
